<template>
    <div class="update-photo">
        <img :src="image" ref="image" />
        <van-nav-bar
            class="toolbar"
            left-text="取消"
            right-text="确定"
            @click-left="$emit('close')"
            @click-right="onClickRight"
        ></van-nav-bar>
    </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

export default {
    components: {},
    props: {
        file: {
            // type: Object,
            required: true
        }
    },
    data () {
        return {
            // 裁剪器实例化
            cropper: null,
            // 预览图片  转换为 blob 数据
            image: window.URL.createObjectURL(this.file)
        }
    },
    created () { },
    mounted () {
        // 获取需要裁切的图片 DOM
        const image = this.$refs.image

        this.cropper = new Cropper(image, {
            viewMode: 1,
            dragMode: 'move',
            aspectRatio: 1,
            cropBoxMovable: false,
            cropBoxResizable: false,
            background: false,
            movable: true
        })
    },
    computed: {},
    methods: {
        getCroppedCanvas () {
            return new Promise(resolve => {
                this.cropper.getCroppedCanvas().toBlob((file) => {
                    resolve(file)
                })
            })
        },
        // 修改头像
        async onClickRight () {
            this.$toast.loading({
                message: '修改中...',
                forbidClick: true,
                duration: 0 // 0 表示持续展示
            })

            // Content-Type 是 multipart/form-data 必须提交 FormData 数据对象，专门用于文件上传
            const file = await this.getCroppedCanvas()

            const fd = new FormData()
            fd.append('photo', file)

            try {
                await updateUserPhoto(fd)

                // 更新父组件的用户头像
                this.$emit('update-photo', window.URL.createObjectURL(file))

                this.$emit('close')
                this.$toast.success('修改成功!')
            } catch (error) {
                this.$toast.fail('修改失败!')
            }
        }
    },
    watch: {}
}
</script>

<style scoped>
.toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #000;
}
</style>
